package com.test.springboot.springboot3testdemo3.service;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import jakarta.annotation.PostConstruct;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

/**
 * Created with IntelliJ IDEA.
 *
 * @author： liuziyang
 * @date： 2024/9/13-12:53
 * @description：
 * @modifiedBy：
 * @version: 1.0
 */
// @Service("threadPoolMonitorService")
public class ThreadPoolMonitorService {
  private static final Logger LOGGER = LoggerFactory.getLogger(ThreadPoolMonitorService.class);

  @Autowired
  @Qualifier("threadPoolExecutor")
  private ThreadPoolExecutor executor;

  @PostConstruct
  public void init() {
    ScheduledExecutorService scheduledExecutorService =
        new ScheduledThreadPoolExecutor(
            1,
            new ThreadFactoryBuilder()
                .setNameFormat("print-pool-status-%d")
                .setDaemon(true)
                .build());
    scheduledExecutorService.scheduleAtFixedRate(
        () -> {
          LOGGER.info(
              "========================= \n"
                  + "ThreadPool Size: [{}]\n"
                  + "Active Threads: {}\n"
                  + "Number of Tasks : {}\n"
                  + "Number of Tasks in Queue: {}\n"
                  + "=========================",
              executor.getPoolSize(),
              executor.getActiveCount(),
              executor.getCompletedTaskCount(),
              executor.getQueue().size());
        },
        0,
        60,
        TimeUnit.SECONDS);
  }
}
